﻿using Architecture.Domain.Services.Interface;
using Architecture.Domain.TraceabilityManage;
using Architecture.Domian.Common;
using Architecture.Domian.DTO;
using Architecture.Domian.Entity;
using Architecture.Repository;
using Architecture.Repository.Impl;
using Architecture.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.Domain.Services.Impl
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IRepository<UserRoleRelation> _roleRelationRepository;

        public UserService(IUserRepository userRepository, IRoleRepository roleRepository, IRepository<UserRoleRelation> roleRelationRepository)
        {
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _roleRelationRepository = roleRelationRepository;
        }

        public async Task<int> BatchInsertData(List<UserInfo> userInfos)
        {
            var res = 0;
            foreach (var userInfo in userInfos)
            {
                res += await _userRepository.AddAsync(userInfo);
            }
            return res;
        }

        public async Task<PageResult<UserInfoDTO>> GetPage(int size, int index)
        {
            var query = await _userRepository.GetAsync(x => !x.IsDelete);
            var datas = query.Select(x => new UserInfoDTO
            {
                UserId = x.UserId,
                LoginName = x.LoginName,
                UserGender = x.UserGender,
                CreatePerson = x.CreatePerson,
                CreateDate = x.CreateDate,
                RevisePerson = x.RevisePerson,
                ReviseDate = x.ReviseDate,
                UserProvince = x.UserProvince,
                UserCity = x.UserCity,
                UserArea = x.UserArea,
                FullAddress = x.FullAddress,
            }).ToArray();

            foreach (var item in datas)
            {
                var relationList = await _roleRelationRepository.GetAsync(x => x.UserId.Equals(item.UserId));
                if (relationList == null) continue;
                var roleIds = relationList.Select(x => x.RoleId).ToArray();
                var roleList = await _roleRepository.GetAsync(x => roleIds.Contains(x.RoleId));
                var roleNames = roleList.Select(x => x.RoleName).ToArray();
                item.RoleNames = String.Join("，", roleNames);
            }

            int totalCount = datas.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / size);

            datas = datas.OrderByDescending(x => x.UserId).Skip(size * (index - 1)).Take(size).ToArray();

            return new PageResult<UserInfoDTO>
            {
                TotalCount = totalCount,
                PageCount = pageCount,
                Datas = datas.ToList()
            };
        }

        public async Task<UserInfo> GetUserInfoByUserId(int userId)
        {
            var res = await _userRepository.GetByIdAsync(userId);
            return res;
        }

        public async Task<int> LogicDelete(int userId)
        {
            // 通过用户Id获取用户信息
            var userInfo = await _userRepository.GetByIdAsync(userId);
            // 用户是否删除标志修改
            userInfo.IsDelete = true;
            // 数据库持久化数据（更新）
            var res = await _userRepository.UpdateAsync(userInfo);
            return res;
        }

        public async Task<int> UpdateUserInfo(UserInfo user)
        {
            // 用户名重复性验证(    坑：判断是否为当前用户修改信息     )
            var exist = await _userRepository.GetByFuncAsync(x => x.LoginName.Equals(user.LoginName) && x.UserId != user.UserId);
            if (exist != null)
            {
                return -1; // 用户名重复
            }
            user.RevisePerson = "李四";
            user.ReviseDate = DateTime.Now;
            // 数据库持久化数据（更新）
            var res = await _userRepository.UpdateAsync(user);
            return res;
        }

        public async Task<int> UserInsert(UserInfo user)
        {
            // 用户名重复性验证(使用any,使用表达式树查询)
            var exist = await _userRepository.GetByFuncAsync(x => x.LoginName.Equals(user.LoginName));
            if (exist != null)
            {
                return -1; // 用户名重复
            }
            // 创建人、创建时间默认值
            user.CreatePerson = "张三";
            user.CreateDate = DateTime.Now;
            user.RevisePerson = null;
            user.ReviseDate = null;
            // 数据库持久化数据（添加）
            var res = await _userRepository.AddAsync(user);
            return res;
        }

        public async Task<CodeDto> Login(UserDTO user)
        {
            var userInfo = await _userRepository.GetByFuncAsync(x => x.PassWord == user.passWord && x.LoginName == user.loginName);

            if (userInfo == null)
            {
                return new CodeDto
                {
                    Code = 0,
                    Msg = "账号或密码不正确",
                    Token = "",
                    UserName = "",
                    UId = 0
                };
            }

            return new CodeDto
            {
                Code = 1,
                Msg = "登录成功",
                Token = "",
                UserName = userInfo.LoginName,
                UId = userInfo.UserId
            };
        }
    }
}
